package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.pinlunvo.UcenterMember;
import com.atguigu.eduservice.client.UcenterClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-02-06
 */
@RestController
@RequestMapping("/eduservice/comment")
//@CrossOrigin
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;

    //注入（ucenter模块的）ucenterClient
    @Autowired
    private UcenterClient ucenterClient;

    //1、根据课程id查询评论列表
    @ApiOperation(value = "评论分页列表")
    @GetMapping("{page}/{limit}")
    public R index(@PathVariable("page") long page,@PathVariable("limit") long limit,String courseId){
        Page<EduComment> pageParam=new Page<>(page,limit);

        QueryWrapper<EduComment> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",courseId);

        commentService.page(pageParam,wrapper);

        List<EduComment> records = pageParam.getRecords();

        HashMap<String ,Object> map=new HashMap<>();
        map.put("items", records);//每页数据集合
        map.put("current", pageParam.getCurrent());//当前页
        map.put("pages", pageParam.getPages());//总页数
        map.put("size", pageParam.getSize());//每页记录数
        map.put("total", pageParam.getTotal());//总记录数
        map.put("hasNext", pageParam.hasNext());//是否有下一页
        map.put("hasPrevious", pageParam.hasPrevious());//是否有上一页

        return R.ok().data(map);
    }


    @ApiOperation(value = "添加评论")
    //2、（添加评论）根据从token字符串获取 用户id：memberId，然后调用ucenter模块的 getInfo：根据用户id获取用户信息
    @PostMapping("auth/save")
    public R save(@RequestBody EduComment eduComment, HttpServletRequest request){
        //从token字符串获取 用户id：memberId
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //判断登录
        if(StringUtils.isEmpty(memberId)) {
            return R.error().code(28004).message("请登录");
        }
        eduComment.setMemberId(memberId);
        //调用ucenter模块的 getInfo：根据用户id获取用户信息
        UcenterMember ucenterInfo = ucenterClient.getInfo(memberId);

        eduComment.setNickname(ucenterInfo.getNickname());
        eduComment.setAvatar(ucenterInfo.getAvatar());

        commentService.save(eduComment);
        return R.ok();
    }

}

